﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TableProto;

/** 
 * @author mcx
 * @date 2018-1-11
 * @version 1.0 
 * Description: 英语游戏管理类
 *  
 * ......................我佛慈悲...................... 
 *                       _oo0oo_ 
 *                      o8888888o 
 *                      88" . "88 
 *                      (| -_- |) 
 *                      0\  =  /0 
 *                    ___/`---'\___ 
 *                  .' \\|     |// '. 
 *                 / \\|||  :  |||// \ 
 *                / _||||| -卍-|||||- \ 
 *               |   | \\\  -  /// |   | 
 *               | \_|  ''\---/''  |_/ | 
 *               \  .-\__  '-'  ___/-. / 
 *             ___'. .'  /--.--\  `. .'___ 
 *          ."" '<  `.___\_<|>_/___.' >' "". 
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | | 
 *         \  \ `_.   \_ __\ /__ _/   .-` /  / 
 *     =====`-.____`.___ \_____/___.-`___.-'===== 
 *                       `=---=' 
 *                        
 *..................佛祖开光 ,永无BUG................... 
 *  
 */



public class StudyEnglishManager : MonoSingleton<StudyEnglishManager>, IEasyLoading, IEasyAudio
{

    public enum EGameState
    {
        None,
        Playing,
        Exit,
    }

    //private SelectLetterController selectController = new SelectLetterController();
    private SelectLetterController2D selectController = new SelectLetterController2D();
    private LawnGameController lawnGC = new LawnGameController();    // 草地场景游戏管理
    private SeaGameController seaGC = new SeaGameController();    // 海底场景游戏管理
    private PaddyfieldGameController paddyfieldGC = new PaddyfieldGameController();    // 麦田场景游戏管理
    private SnowGameController snowGC = new SnowGameController();    // 雪地场景游戏管理

    private int m_letterIndex;
    public int playingLetter
    {
        get { return m_letterIndex; }
    }

    private EGameState gameState;


    void Update()
    {
        if (Application.isEditor)
        {
            if (Input.GetMouseButtonDown(0))
            {
                EventBus.Instance.BroadCastEvent(EventID.ON_MOUSE_BUTTON_DOWN);
            }
            if (Input.GetMouseButton(0))
            {
                EventBus.Instance.BroadCastEvent(EventID.ON_MOUSE_BUTTON_HOVER);
            }
            if (Input.GetMouseButtonUp(0))
            {
                EventBus.Instance.BroadCastEvent(EventID.ON_MOUSE_BUTTON_UP);
            }
        }
        else
        {
            if (Input.touchCount > 0)
            {
                if (Input.GetTouch(0).phase == TouchPhase.Began)
                {
                    EventBus.Instance.BroadCastEvent(EventID.ON_MOUSE_BUTTON_DOWN);
                }
                if (Input.GetTouch(0).phase == TouchPhase.Stationary || Input.GetTouch(0).phase == TouchPhase.Moved)
                {
                    EventBus.Instance.BroadCastEvent(EventID.ON_MOUSE_BUTTON_HOVER);
                }
                if (Input.GetTouch(0).phase == TouchPhase.Ended)
                {
                    EventBus.Instance.BroadCastEvent(EventID.ON_MOUSE_BUTTON_UP);
                }
            }
        }


        selectController.OnUpdate(Time.deltaTime);
        lawnGC.OnUpdate();
        seaGC.OnUpdate();
        paddyfieldGC.OnUpdate();
        snowGC.OnUpdate();
        
    }


    public void StartGame()
    {
        gameState = EGameState.None;
        AddEvent();
        LoadScene(true);

        this.PlayMusicEx(StudyAudioName.t_30001);
    }

    public void ExitGame()
    {
        gameState = EGameState.Exit;
        RemoveEvent();
        snowGC.ExitGame();
        seaGC.ExitGame();
        paddyfieldGC.ExitGame();
        lawnGC.ExitGame();
        DestroyScene();
    }

    private void AddEvent()
    {
        EventBus.Instance.AddEventHandler(EventID.ON_ENGLISH_WINDOW_BTN_RETURN_CLICK, OnEnglishWindowReturnClick);
        EventBus.Instance.AddEventHandler<int, EEnglishGameEnum>(EventID.ON_ENGLISH_SELECT_GAME, OnEnglishGameSelect);
    }

    private void RemoveEvent()
    {
        EventBus.Instance.RemoveEventHandler(EventID.ON_ENGLISH_WINDOW_BTN_RETURN_CLICK, OnEnglishWindowReturnClick);
        EventBus.Instance.RemoveEventHandler<int, EEnglishGameEnum>(EventID.ON_ENGLISH_SELECT_GAME, OnEnglishGameSelect);
    }

    private void OnEnglishWindowReturnClick()
    {
        if (gameState == EGameState.Playing || gameState == EGameState.Exit)
            return;

        gameState = EGameState.Exit;

        EnglishLediAnimationWindow.Instance.StopAnimation();
        EnglishSelectLetterWindow.Instance.UpdateLockState(true);
        if (!SDKManager.Instance.IsShowGZH())
        {
            GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
        }
        else
        {
            WindowManager.Instance.OpenWindow(WinNames.EnglishMioPanel, EWindowFadeEnum.None, EWindowLayerEnum.PopupLayer);
            EnglishMioWindow.Instance.AddCloseEvent(() =>
            {

                GameStateManager.Instance.GotoState(GameStateName.MAIN_STATE);
            });
        }
    }

    private void OnEnglishGameSelect(int letterIndex, EEnglishGameEnum type)
    {
        //Debug.LogError("------------------ OnEnglishGameSelect");

        if (type == EEnglishGameEnum.None)
        {
            this.StartLoadingAndEndEx(() =>
            {
                selectController.LoadScene(OnSelectLetterComplete);
                WindowManager.Instance.CloseWindow(WinNames.EnglishSelectGamePanel);
                LoadScene(false);
                gameState = EGameState.None;
            });
            return;
        }

        this.PlayAudioEx(StudyAudioName.t_32002);
        this.StartLoadingAndEndEx(() => {

            WindowManager.Instance.CloseWindow(WinNames.EnglishSelectGamePanel);
            selectController.DestroyScene();
            EnglishLevelInfo info = TableProtoLoader.EnglishLevelInfoDict[FEnglishTool.GetEnglishDataID(letterIndex)];

            if (info != null)
            {
                EEnglishSceneType playmode = (EEnglishSceneType)info.play_mode;
                switch (playmode)
                {
                    // 草地
                    case EEnglishSceneType.Lawn:
                        //FTimeTool.Record("OnEnglishGameSelect Lawn");
                        lawnGC.StartGame(letterIndex, info, type, OnControllerCallback);
                        //FTimeTool.Record("OnEnglishGameSelect Lawn");
                        break;
                    // 海底
                    case EEnglishSceneType.Sea:
                        seaGC.StartGame(letterIndex, info, type, OnControllerCallback);
                        break;
                    // 麦田
                    case EEnglishSceneType.Paddyfield:
                        paddyfieldGC.StartGame(letterIndex, info, type, OnControllerCallback);
                        break;
                    // 雪地
                    case EEnglishSceneType.Snow:
                        //FTimeTool.Record("OnEnglishGameSelect Snow");
                        snowGC.StartGame(letterIndex, info, type, OnControllerCallback);
                        //FTimeTool.Record("OnEnglishGameSelect Snow");
                        break;
                }
                gameState = EGameState.Playing;
            }
            else
            {
                Debug.LogError("Request start game faild! LetterID: " + FEnglishTool.GetEnglishDataID(letterIndex));
            }

        });
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="letterID">字母ID</param>
    private void PlayGameFormLetterID(int letterIndex)
    {
        m_letterIndex = letterIndex;

        this.StartLoadingAndEndEx(() =>
        {
            selectController.DestroyScene();
            // 先选择游戏
            WindowManager.Instance.OpenWindow(WinNames.EnglishSelectGamePanel, letterIndex);
        });
    }

    private void OnControllerCallback(bool isComplete, bool isNext)
    {
        //LoadScene();
        //selectController.UpdateLockState(true);
        if (!isComplete)
        {
            snowGC.ExitGame();
            seaGC.ExitGame();
            paddyfieldGC.ExitGame();
            lawnGC.ExitGame();
        }
        gameState = EGameState.None;

        ResourceManager.Instance.UnloadUnusedAssets();
        int nextLetterIndex = isNext ? m_letterIndex + 1 : m_letterIndex;
        if (nextLetterIndex > 25)
            nextLetterIndex = 0;
        WindowManager.Instance.OpenWindow(WinNames.EnglishSelectGamePanel, nextLetterIndex);
    }

    private void OnSelectLetterComplete(int letterIndex)
    {
        if (gameState == EGameState.Exit)
            return;
        PlayGameFormLetterID(letterIndex);
    }

    private void LoadScene(bool isFirstLoad)
    {
        selectController.LoadScene(OnSelectLetterComplete);
        WindowManager.Instance.OpenWindow(WinNames.EnglishPanel);
        WindowManager.Instance.OpenWindow(WinNames.EnglishLediAnimationPanel, EWindowLayerEnum.PopupLayer);

        if (isFirstLoad)
        {
            EnglishLediAnimationWindow.Instance.PlayLediTalkJSAnimation(EnglishLediAnimationWindow.ELediFadeInType.BottomLeft, this.GetAudioNameEx(StudyAudioName.t_32008));
            EnglishSelectLetterWindow.Instance.ResetLetterProgress();
        }
        else
        {
            EnglishSelectLetterWindow.Instance.OnSDKEnd();
        }
    }

    private void DestroyScene()
    {
        selectController.DestroyScene();
        WindowManager.Instance.CloseWindow(WinNames.EnglishPanel);
        WindowManager.Instance.CloseWindow(WinNames.EnglishLediAnimationPanel);
    }

}
